package com.surelution.projects.crm

class UserPageEntryController {

    def index = {
		def userId = params.userId
		if(userId) {
			def user = User.get(userId)
			if(user) {
				def userPages = UserPageEntry.findAllByUser(user)
				def allCategories = PageEntry.findAllByIsLeaf(false)
				[userPages:userPages, allCategories:allCategories]
			}
		}
	}
	
	def save = {
		def userId = params.userId
		def needEntries
		if(params.pageEntry instanceof String) {
			needEntries = [params.pageEntry]
		} else {
			needEntries = params.pageEntry
		}
		def user = User.get(userId)
		def userPages = UserPageEntry.findAllByUser(user)

		userPages.each {page->
			page.delete(flush:true)
		}
		needEntries.each {needId->
			def page = PageEntry.get(needId)
			def upe = new UserPageEntry(user:user, entry:page)
			upe.save(flush:true)
		}
		
		redirect(action:index, params:[userId:userId])
	}
	
	def copy = {
		def userId = params.userId
		def copyFrom = User.get(params.copyFrom)
		if(copyFrom) {
			def copyPageEntries = UserPageEntry.findAllByUser(copyFrom)
			if(copyPageEntries) {
				def user = User.get(userId)
				def userPages = UserPageEntry.findAllByUser(user)

				if(userPages) {
					userPages.each {page->
						page.delete(flush:true)
					}
				}

				copyPageEntries.each {need->
					def page = PageEntry.get(need.entry.id)
					def upe = new UserPageEntry(user:user, entry:page)
					upe.save(flush:true)
				}
			}
		}

		redirect(action:index, params:[userId:userId])
	}
}
